/*
 * Copyright (C) 2012 Martin Řehánek <rehan at mzk.cz>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.kramerius.k4audiopoc;

import cz.mzk.kramerius.k4audiopoc.urlMapping.CachingFedoraUrlManager;
import cz.mzk.kramerius.k4audiopoc.urlMapping.RepositoryUrlManager;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Martin Řehánek <Martin.Rehanek at mzk.cz>
 */
@WebServlet(name = "AudioProxyServlet", urlPatterns = {"/audioProxy/*"})
public class AudioProxyServlet extends HttpServlet {// implements SingleThreadModel {

    private static final Logger LOGGER = Logger.getLogger(AudioProxyServlet.class.getName());
    private RepositoryUrlManager urlManager;

    @Override
    public void init() {
        LOGGER.log(Level.INFO, "initializing {0}", AudioProxyServlet.class.getName());
        try {
            urlManager = new CachingFedoraUrlManager(true);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void destroy() {
        LOGGER.log(Level.INFO, "shutting down {0}", AudioProxyServlet.class.getName());
        urlManager.close();
        AudioHttpRequestForwarder.destroy();
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //System.err.println("counter: " + ServletRequestCounter.incrementAndGetCounter());
            LOGGER.log(Level.INFO, "GET {0}", request.getPathInfo());
            AudioStreamId id = AudioStreamId.fromPathInfo(request.getPathInfo());
            LOGGER.info(id.toString());
            URL url = urlManager.getAudiostreamRepositoryUrl(id);
            if (url == null) {
                throw new ServletException("url for id " + id.toString() + " is null");
            }
            LOGGER.info(url.toString());
            //appendTestHeaders(response, id, url); //testovaci hlavicky
            AudioHttpRequestForwarder forwarder = new AudioHttpRequestForwarder(request, response);
            forwarder.forwardGetRequest(url);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AudioProxyServlet.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServletException(ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>HEAD</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            LOGGER.log(Level.INFO, "HEAD {0}", request.getPathInfo());
            AudioStreamId id = AudioStreamId.fromPathInfo(request.getPathInfo());
            LOGGER.info(id.toString());
            URL url = urlManager.getAudiostreamRepositoryUrl(id);
            if (url == null) {
                throw new ServletException("url for id " + id.toString() + " is null");
            }
            LOGGER.info(url.toString());
            //appendTestHeaders(response, id, url); //testovaci hlavicky
            AudioHttpRequestForwarder forwarder = new AudioHttpRequestForwarder(request, response);
            forwarder.forwardHeadRequest(url);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AudioProxyServlet.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServletException(ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Kramerius 4 Audio proxy servlet";
    }

    private void appendTestHeaders(HttpServletResponse response, AudioStreamId id, URL url) {
        response.setHeader("Test.ImageId", id.toString());
        response.setHeader("Test.ImageLink", url.toString());
    }
}
